import AdBanner from '@/components/AdBanner';
import CheckableTag from '@/components/CheckableTag';
import ScrollPageList from '@/components/ScrollPageList';
import { evaluationV1ControllerIndex } from '@/services/auto/evaluation';
import { css } from '@emotion/react';
import { useModel } from '@umijs/max';
import { Card, Descriptions, InputNumber, List, Space } from 'antd';
import { DescriptionsItemType } from 'antd/es/descriptions';
import { GetScrollPageParam } from 'common/interface';
import {
  CarouselPositionCode,
  EvaluationCategory,
  SpecificationValueType,
} from 'common/utils/data';
import { Fragment, ReactNode, useEffect, useState } from 'react';
import Item from './Item';
import { useMemoizedFn, useUpdateEffect } from 'ahooks';
import Rate from '@/components/Rate';

const bannerMap: Record<
  EvaluationCategory,
  [CarouselPositionCode, CarouselPositionCode]
> = {
  [EvaluationCategory.EARBUDS]: [
    CarouselPositionCode.EARBUDS_LIST_TOP_LEFT,
    CarouselPositionCode.EARBUDS_LIST_TOP_RIGHT,
  ],
  [EvaluationCategory.SOUND_SOURCE]: [
    CarouselPositionCode.SOUND_SOURCE_LIST_TOP_LEFT,
    CarouselPositionCode.SOUND_SOURCE_LIST_TOP_RIGHT,
  ],
};

export default function EvaluationArticleList({
  category,
  keyword,
  defaultSpecifications,
  hideSpecificationNames,
}: {
  category?: EvaluationCategory;
  keyword?: string;
  /**
   * @description 默认规格属性
   * 两点作用:
   * 1. 默认查询规格参数
   * 2. 过滤规格选项
   */
  defaultSpecifications?: API.EvaluationIndexDtoSpecificationItem[];
  /** 隐藏规格名称 */
  hideSpecificationNames?: string[] | true;
}) {
  const { data: specifications, loading: specificationsLoading } =
    useModel('specification');

  const { data: brands, loading: brandsLoading } = useModel('brand');

  const [evaluationBrandUuids, setEvaluationBrandUuids] = useState<string[]>();

  const [evaluationPrice, setEvaluationPrice] = useState<string[]>();
  const [evaluationCustomPrice, setEvaluationCustomPrice] =
    useState<number[]>();

  const [evaluationSpecs, setEvaluationSpecs] =
    useState<Exclude<API.EvaluationIndexDto['specifications'], undefined>>();

  const [searchParam, setSearchParam] = useState<
    GetScrollPageParam<API.EvaluationIndexDto>
  >({
    category,
    keyword,
    specifications: defaultSpecifications,
  });

  useUpdateEffect(() => {
    setSearchParam((ori) => {
      return {
        ...ori,
        keyword,
      };
    });
  }, [keyword]);

  const setSearchParamSpecifications = useMemoizedFn((sourceSpecifications?: API.EvaluationIndexDtoSpecificationItem[]) => {
    // 重置defaultSpecifications,仅用于查询条件
    const searchSpecifications = sourceSpecifications ? sourceSpecifications.slice() : [];
    defaultSpecifications?.forEach(
      (specificationItem) => {
        if (
          !searchSpecifications.find(
            (newItem) =>
              newItem.specificationUuid ===
              specificationItem.specificationUuid,
          )
        ) {
          searchSpecifications.push(specificationItem);
        }
      },
    );
    setSearchParam((ori) => {
      return {
        ...ori,
        specifications: searchSpecifications,
      };
    });
  })

  return (
    <Fragment>
      {category && <div className="flex gap-[16px]">
        {bannerMap[category].map((item) => {
          return (
            <AdBanner
              key={item}
              positionCode={item}
              width="658px"
              height="100px"
              ossFormatParam="?x-oss-process=image/resize,w_658,h_100"
              wrapClassName="mb-[16px] flex-1 min-w-0"
            />
          );
        })}
      </div>}

      {
        hideSpecificationNames === true ? null : (
          <Card
            classNames={{
              body: 'py-[16px]',
            }}
            loading={specificationsLoading}
            className="mb-[16px]"
          >
            <Descriptions
              bordered
              size="small"
              column={1}
              styles={{
                label: {
                  width: 110,
                },
              }}
              items={[
                {
                  key: 'brand',
                  label: '品牌',
                  children: (
                    <CheckableTag
                      options={brands?.map((item) => {
                        return {
                          label: item.title,
                          value: item.uuid,
                        };
                      })}
                      value={evaluationBrandUuids}
                      onChange={(value) => {
                        setEvaluationBrandUuids(value);
                        setSearchParam((origin) => {
                          return {
                            ...origin,
                            brandUuids: value?.length ? value : undefined,
                          };
                        });
                      }}
                    />
                  ),
                },
                {
                  key: 'price',
                  label: '价格',
                  children: (
                    <Fragment>
                      <CheckableTag
                        options={[
                          null as any,
                          '0-199',
                          '200-499',
                          '500-999',
                          '1000-2499',
                          '2500-4999',
                          '5000-7999',
                          '8000-13999',
                        ].map((item) => {
                          return {
                            label: item ?? '未公布',
                            value: item,
                          };
                        })}
                        value={evaluationPrice}
                        onChange={(value) => {
                          setEvaluationPrice(value);
                          if (value) {
                            setEvaluationCustomPrice(undefined);
                            const prices = value.map((item) => {
                              if(item){
                                return item.split('-').map((it) => {
                                  return Number(it);
                                });
                              }
                              return [null,null];
                            });
                            setSearchParam((origin) => {
                              return {
                                ...origin,
                                prices,
                              };
                            });
                          } else {
                            setSearchParam((origin) => {
                              return {
                                ...origin,
                                prices: undefined,
                              };
                            });
                          }
                        }}
                      />
                      <Space.Compact>
                        <InputNumber
                          size="small"
                          placeholder="最小"
                          value={evaluationCustomPrice?.[0]}
                          onChange={(value) => {
                            setEvaluationCustomPrice((origin) => {
                              const newOrigin = origin?.slice() ?? [null, null];
                              newOrigin[0] = value as number;
                              return newOrigin;
                            });
                          }}
                          onPressEnter={() => {
                            if (
                              evaluationCustomPrice?.[0] ||
                              evaluationCustomPrice?.[1]
                            ) {
                              setEvaluationPrice(undefined);
                            }
                            setSearchParam((origin) => {
                              return {
                                ...origin,
                                prices:
                                  evaluationCustomPrice?.[0] !== null ||
                                    evaluationCustomPrice?.[1] !== null
                                    ? [evaluationCustomPrice]
                                    : undefined,
                              };
                            });
                          }}
                        />
                        <span className="mx-[2px]">~</span>
                        <InputNumber
                          size="small"
                          placeholder="最大"
                          value={evaluationCustomPrice?.[1]}
                          onChange={(value) => {
                            setEvaluationCustomPrice((origin) => {
                              const newOrigin = origin?.slice() ?? [null, null];
                              newOrigin[1] = value as number;
                              return newOrigin;
                            });
                          }}
                          onPressEnter={() => {
                            if (
                              evaluationCustomPrice?.[0] ||
                              evaluationCustomPrice?.[1]
                            ) {
                              setEvaluationPrice(undefined);
                            }
                            setSearchParam((origin) => {
                              return {
                                ...origin,
                                prices:
                                  evaluationCustomPrice?.[0] !== null ||
                                    evaluationCustomPrice?.[1] !== null
                                    ? [evaluationCustomPrice]
                                    : undefined,
                              };
                            });
                          }}
                        />
                      </Space.Compact>
                    </Fragment>
                  ),
                },
                ...((specifications
                  ?.filter(
                    (item) =>
                      item.openSearch &&
                      item.category === category &&
                      !hideSpecificationNames?.includes(item.name),
                  )
                  .map((item) => {
                    let field: ReactNode;
                    if (item.valueType === SpecificationValueType.SELECT) {
                      field = (
                        <CheckableTag
                          key={item.uuid}
                          options={item.extra.options.filter(
                            // 过滤规格选项
                            (option: { label: string; value: string }) =>
                              defaultSpecifications?.some(
                                (specificationItem) =>
                                  specificationItem.specificationUuid !== item.uuid,
                              ) ||
                              defaultSpecifications?.some((specificationItem) =>
                                specificationItem.value.includes(option.value),
                              ),
                          )}
                          value={
                            evaluationSpecs?.find(
                              (specification) =>
                                item.uuid === specification.specificationUuid,
                            )?.value
                          }
                          onChange={(value) => {
                            setEvaluationSpecs((origin) => {
                              const newOrigin = origin?.slice() ?? [];
                              const currentIndex = newOrigin?.findIndex(
                                (specification) =>
                                  item.uuid === specification.specificationUuid,
                              );
                              if (currentIndex >= 0) {
                                if (value?.length) {
                                  newOrigin[currentIndex].value = value;
                                } else {
                                  newOrigin.splice(currentIndex, 1);
                                }
                              } else {
                                if (value?.length) {
                                  newOrigin.push({
                                    specificationUuid: item.uuid,
                                    value,
                                  });
                                }
                              }

                              setSearchParamSpecifications(newOrigin);
                              return newOrigin;
                            });
                          }}
                        />
                      );
                    }

                    if (item.valueType === SpecificationValueType.NUMBER) {
                      field = (
                        <Space.Compact key={item.uuid}>
                          <InputNumber
                            size="small"
                            placeholder="最小"
                            onChange={(value) => {
                              setEvaluationSpecs((origin) => {
                                const newOrigin = origin?.slice() ?? [];
                                const currentIndex = newOrigin.findIndex(
                                  (specification) =>
                                    item.uuid === specification.specificationUuid,
                                );
                                if (currentIndex >= 0) {
                                  if (value !== undefined && value !== null) {
                                    newOrigin[currentIndex].value[0] = value;
                                  } else if (
                                    newOrigin[currentIndex].value[1] ===
                                    undefined ||
                                    newOrigin[currentIndex].value[1] === null
                                  ) {
                                    newOrigin.splice(currentIndex, 1);
                                  } else {
                                    newOrigin[currentIndex].value[0] = null;
                                  }
                                } else {
                                  if (value !== undefined && value !== null) {
                                    newOrigin.push({
                                      specificationUuid: item.uuid,
                                      value: [value],
                                    });
                                  }
                                }
                                return newOrigin;
                              });
                            }}
                            onPressEnter={() => {
                              setSearchParamSpecifications(evaluationSpecs);
                            }}
                          />
                          <span className="mx-[2px]">~</span>
                          <InputNumber
                            size="small"
                            placeholder="最大"
                            onChange={(value) => {
                              setEvaluationSpecs((origin) => {
                                const newOrigin = origin.slice();
                                const currentIndex = origin.findIndex(
                                  (specification) =>
                                    item.uuid === specification.specificationUuid,
                                );
                                if (currentIndex >= 0) {
                                  if (value !== undefined && value !== null) {
                                    newOrigin[currentIndex].value[1] = value;
                                  } else if (
                                    newOrigin[currentIndex].value[0] ===
                                    undefined ||
                                    newOrigin[currentIndex].value[0] === null
                                  ) {
                                    newOrigin.splice(currentIndex, 1);
                                  } else {
                                    newOrigin[currentIndex].value[1] = null;
                                  }
                                } else {
                                  if (value !== undefined && value !== null) {
                                    newOrigin.push({
                                      specificationUuid: item.uuid,
                                      value: [null, value],
                                    });
                                  }
                                }
                                return newOrigin;
                              });
                            }}
                            onPressEnter={() => {
                              setSearchParamSpecifications(evaluationSpecs);
                            }}
                          />
                        </Space.Compact>
                      );
                    }

                    return {
                      key: item.uuid,
                      label: item.name,
                      children: field,
                    };
                  }) ?? []) as DescriptionsItemType[]),
              ]}
            />
          </Card>
        )
      }
      <div
        style={{
          marginLeft: -8,
          marginRight: -8,
        }}
      >
        <ScrollPageList
          param={searchParam}
          service={evaluationV1ControllerIndex}
          order={{
            orderBy: 'article.publishTime',
            direction: 'DESC',
          }}
          emptyDesc="暂无数据 可联系送测，Q群：928537203"
        >
          {(data) => {
            return (
              <Rate.TagProvider>
                <List
                  grid={{ gutter: 16, column: 4 }}
                  dataSource={data}
                  rowKey="uuid"
                  renderItem={(item) => {
                    return <Item item={item} />;
                  }}
                  css={css`
                  &
                    > .ant-spin-nested-loading
                    > .ant-spin-container
                    > .ant-row {
                    margin-left: 0 !important;
                    margin-right: 0 !important;
                  }
                `}
                />
              </Rate.TagProvider>
            );
          }}
        </ScrollPageList>
      </div>
    </Fragment>
  );
}
